<?php
namespace app\api\controller;
use app\common\logic\Logic;
use app\common\logic\UserAccount;
use app\common\model\ChatUsers;
use app\common\model\GiftRecord;
use app\common\model\Job;
use app\common\model\Order;
use app\common\model\RechargeConfig;
use app\common\model\Room;
use app\common\model\SkillApply;
use app\common\model\UserGuard;
use think\Db;
use app\common\model\Users;
use think\helper\Time;
use wheat\Wheat;


class User extends Base
{
    //用户id
    protected $user_id = 0;

    public function _initialize()
    {
        parent::_initialize();
        $url = request()->controller();
        $url .= '/'.request()->action();
        $notIntercept = ['Pays/notify','Pays/wechat'];


        if (!in_array($url,$notIntercept)){
            //支付回调不进行拦截
            $this->user_id = $this->checkToken();

        }

    }


    /**
     * 退出登陆
     */
    public function loginOut()
    {
        cache('token_'.hashid($this->user_id),null);
        api_return(1,'退出成功');
    }




    /**
     * Created by xiaosong
     * E-mail:306027376@qq.com
     * 获取用户会员信息
     */
    protected function userNoble($field = '',$user_id = null,$cache = 15){
        if ($user_id){
            $map['user_id'] = $user_id;
        }else{
            $map['user_id'] = $this->user_id;
        }
        $noble_id =  Db::name('user_extend')->where($map)->value('noble_id');
        $data = Db::name('noble')->where('noble_id',$noble_id)->cache($cache)->find();
        if (strstr($field,',') || empty($field)){
            if (!$field){ return $data; }
            $arr = explode(',',$field);
            foreach ($arr as $v){
                $array[$v] = $data[$v];
            }
        }else{
            return $data[$field];
        }
    }



    /**
     * 获取用户信息
     */
    public function getUser()
    {
        $where['a.user_id'] = $this->user_id;
        $model  = new Users();
        $result = $model->getDetail($where);
        api_return(1, '获取成功', $result);
    }

    /**
     * 查询个人资料
     */
    public function info()
    {
        $model = new Users();
        $data  = $model->getInfo($this->user_id);
        api_return(1,'获取成功',$data);
    }

    /**
     * Created by xiaosong
     * E-mail:306027376@qq.com
     * 形象照修改||添加
     */
    public function editImg()
    {
        $data = request()->only(['img_id','img'],'post');

        if (!$data['img']) api_return(0,'请上传图片');

        $data['update_time'] = time();

        $map['user_id'] = $this->user_id;
        $map['status']  = 1;

        if (is_numeric($data['img_id'])){  //形象照修改

            $map['img_id']  = $data['img_id'];
            $img_id = Db::name('user_img')->where($map)->value('img_id');
            if ($img_id){

                $result = Db::name('user_img')->update($data);
                if ($result){
                    api_return(1,'修改成功',['img_id'=>$data['img_id'],'img'=>$data['img']]);
                }else{
                    api_return(0,'修改失败');
                }
            }
            api_return(0,'非法参数');
        }

        //形象照添加

        $num = Db::name('user_img')->where($map)->count();
        $max = Db::name('extend')->where('id',1)->cache(60)->value('img_max');

        if ($num >= $max){
            api_return(0,'形象照最多只允许上传'.$max.'张');
        }

        $data['create_time'] = time();
        $data['user_id']     = $this->user_id;
        $result = Db::name('user_img')->strict(false)->insert($data);
        if ($result){
            api_return(1,'上传成功',['img_id'=>Db::name('user_img')->getLastInsID(),'img'=>$data['img']]);
        }else{
            api_return(0,'上传失败');
        }

    }

    /**
     * Created by xiaosong
     * E-mail:4155433@gmail.com
     * 形象照删除
     */
    public function delImg()
    {
        $map = request()->only(['img_id'],'post');
        $map['user_id'] = $this->user_id;
        $map['type'] = 1;
        $map['status'] = 1;
        $img_id = Db::name('user_img')->where($map)->value('img_id');
        if (!$img_id) api_return(0,'参数错误');
        $result = Db::name('user_img')->delete($img_id);
        if ($result) api_return(1,'删除成功');
        api_return(0,'删除失败');
    }


    /**
     * Created by xiaosong
     * E-mail:306027376@qq.com
     * 个人资料编辑
     */
    public function editInfo()
    {
        $data = request()->only(['header_img','nick_name','sex','job','sign','tag','birthday']);

        if ($data['header_img']){
            $cache = cache('header_img'.$this->user_id);
            //TODO 上线后解开注释
//            if ($cache) api_return(0,'头像每天只能修改一次!');
            cache('header_img'.$this->user_id,1,todayEndTime());
        }
        if ($data['nick_name']){
            $cache = cache('nick_name'.$this->user_id);
            //TODO 上线后解开注释
//            if ($cache) api_return(0,'昵称每天只能修改一次!');
            cache('nick_name'.$this->user_id,1,todayEndTime());
        }

        $model  = new \app\common\logic\Users();

        $data['id'] = $this->user_id;

        $result = $model->change($data);

        if ($result){
            api_return(1,'修改成功');
        }
        api_return(0,$model->getError());
    }


    /**
     * Created by xiaosong
     * E-mail:306027376@qq.com
     * 用户个人详情
     */
    protected function userDetail($user_id)
    {

        $model = new Users();
        $userInfo = $model->getInfo($user_id);
        $userInfo['constellation'] = get_constellation($userInfo['birthday']);
        $userInfo['age'] = getAge($userInfo['birthday']).'岁';

        $extra = $this->userExtra('place,online_status,online_time');

        $data  = array_merge($userInfo->getData(),$extra);

       if ($data['online_status']){
           $data['status'] = '当前在线';
       }else{
           $data['status'] = formatTime($data['online_time']);
       }

        $map['status']  = 1;
        $map['user_id'] = $user_id;

        $data['vod']     = Db::name('vod')->where($map)->field('pid,play_url,play_num,img')->select();

        $data['vod_max'] = $this->extend('vod_max');

        $room['a.status'] = 1;
        $room['a.user_id'] = $user_id;

        //TODO 为房间管理员的房间未加入
        $data['room_list'] = (new Room())->room($room);


        $gift['a.status']  = 1;
        $gift['a.to_user'] = $user_id;
        $data['gift_count'] = Db::name('gift_record')->alias('a')->where($gift)->sum('a.num');

        $data['gift_list']  = (new GiftRecord())->giftCount($gift);

        $group['c.type']    = 2;
        $group['c.status']  = 1;
        $group['a.user_id'] = $user_id;
        $group['a.status']  = 1;
        $data['group_list'] = (new ChatUsers())->items($group);





        $data['skill_list'] = self::getSkillList($this->user_id);

        return $data;

    }

    /**
     * Created by xiaosong
     * E-mail:4155433@gmail.com
     * 获取用户可用技能列表
     * @param $user_id
     * @return false|\PDOStatement|string|\think\Collection
     *
     */
    protected static function getSkillList($user_id)
    {
        $map['a.user_id'] = $user_id;
        $map['a.status']  = 1;
        $map['a.is_use']  = 1;
        return (new SkillApply())->getMy($map);
    }


    /**
     * Created by xiaosong
     * E-mail:4155433@gmail.com
     * 聊天界面获取信息
     */
    public function chatInfo()
    {
        $id = dehashid(input('id'));
        if (!is_numeric($id)) api_return(0,'参数错误');
        $rows['skill_list'] = self::getSkillList($id);
        $rows['is_follow']  = self::isFollow($this->user_id,$id);
        api_return(1,'获取成功',$rows);
    }


    /**
     * Created by xiaosong
     * E-mail:4155433@gmail.com
     * 用户自身详情
     */
    public function selfInfo()
    {
        $data = $this->userDetail($this->user_id);

        api_return(1,'获取成功',$data);

    }

    /**
     * Created by xiaosong
     * E-mail:4155433@gmail.comZ
     * 其它用户详情
     */
    public function otherInfo()
    {

        $user_id = dehashid(input('post.id'));

        if (!is_numeric($user_id)){
            api_return(0,'参数错误');
        }elseif ($user_id == $this->user_id){
            api_return(0,'应查询个人详情');
        }

        $data = $this->userDetail($user_id);

        $guard['a.guard_user'] = $user_id;
        $guard['a.status']     = 1;
        $guard['a.end_time']   = ['>',time()];

        $data['guard'] = UserGuard::Best($guard);

        $tag['a.user_id'] = $user_id;
        $tag['a.status']  = ['between','4,5'];

        $data['InterestTag'] = Order::InterestTag($tag);

        $data['is_follow'] = self::isFollow($this->user_id,$user_id);

        api_return(1,'获取成功',$data);
    }

    /**
     * Created by xiaosong
     * E-mail:4155433@gmail.com
     * @param int $user_id
     * @param int $follow_user
     * @return int
     * 获取是否关注用户
     */
    protected static function isFollow( $user_id, $follow_user):int
    {
        $map['user_id']     = $user_id;
        $map['follow_user'] = $follow_user;
        $map['status']      = 1;
        return $follow_id = Db::name('user_follow')->where($map)->value('status')??0;
    }



    /**
     * Created by xiaosong
     * E-mail:306027376@qq.com
     * 获取职业列表
     */
    public function job()
    {
        $model = new Job();
        $rows  = $model->getList();
        api_return(1,'获取成功',$rows);

    }

    /**
     * Created by xiaosong
     * E-mail:4155433@gmail.com
     * 获取用户标签
     */
    public function getTag()
    {
        $map['a.user_id'] = $this->user_id;
        $map['a.status']  = ['between','4,5'];
        $rows = Order::InterestTag($map,true);
        $rows[] = ['tag'=>'处对象'];
        $rows[] = ['tag'=>'处连麦'];
        api_return(1,'获取成功',$rows);
    }



    /**
     * 修改手机号码
     */
    public function changePhone()
    {
        $data = input('post.');
        $userPhone = Db::name('users')->where('user_id',$this->user_id)->value('phone');
        $this->checkCode($userPhone,'原手机号码验证码错误');
        $this->checkCode('newPhone','新手机号码验证码错误','newCode');
        $has = Db::name('users')->where('phone',$data['newPhone'])->value('user_id');
        if ($has) api_return(0,'新手机号码已注册');
        $result = Db::name('users')->where('user_id',$this->user_id)->update(['phone'=>$data['newPhone']]);
        if ($result !== false) {
            api_return(1,'更换手机成功');
        }
        api_return(0,'更换手机失败');
    }

    /**
     * Created by xiaosong
     * E-mail:306027376@qq.com
     * 用户钱包余额
     */
    public function wallet()
    {
        $data = $this->userBalance();

        $map['user_id'] = $this->user_id;
        $map['status']  = 1;

        $data['ID'] = Db::name('user_id')->where($map)->value('ID');

        $data['account_id'] = Db::name('user_account')->where($map)->value('account_id');

        api_return(1,'获取成功',$data);
    }


    /**
     * Created by xiaosong
     * E-mail:306027376@qq.com
     * 用户账户余额
     */
    protected function userBalance($user_id = null)
    {

        if (!$user_id){
            $user_id = $this->user_id;
        }
        $data = Db::name('users')->where('user_id',$user_id)->field('money,cash')->find();
        $data['total'] = bcadd($data['money'],$data['cash'],2);
        return $data;

    }

    /**
     * Created by xiaosong
     * E-mail:4155433@gmail.com
     * 扣除用户账户余额
     */
    protected function moneyDec($money = 0,$user_id = null){
        if (!$user_id){
            $user_id = $this->user_id;
        }
        $balance = $this->userBalance($user_id);
        if ($money > $balance['total']) api_return(0,'余额不足');
        if ($balance['money'] >= $money){
            $result = Db::name('users')->where('user_id',$user_id)->setDec('money',$money);
            if (!$result) api_return(0,'扣款失败');
        }else{
            if ($balance['money'] > 0){
                $next = bcsub($money,$balance['money'],2);
                $result = Db::name('users')->where('user_id',$user_id)->setDec('money',$balance['money']);
                if (!$result) api_return(0,'扣款失败');
            }else{
                $next = $money;
            }
            $result = Db::name('users')->where('user_id',$user_id)->setDec('cash',$next);
            if (!$result){
                Db::name('users')->where('user_id',$user_id)->setInc('money',$balance['money']);
                api_return(0,'扣款失败');
            }
        }
    }



    /**
     * Created by xiaosong
     * E-mail:306027376@qq.com
     * 获取用户账户余额
     */
    public function balance()
    {
        api_return(1,'获取成功',$this->userBalance());
    }


    /**
     * Created by xiaosong
     * E-mail:306027376@qq.com
     * 充值参数获取
     */
    public function rechargeConfig()
    {
        $data['balance'] = $this->userBalance();

        $map['status'] = 1;

        $model = new RechargeConfig();

        $data['rows']  = $model->getRows($map);

        api_return(1,'获取成功',$data);

    }

    /**
     * Created by xiaosong
     * E-mail:306027376@qq.com
     * 获取我的提现账户
     */
    public function account()
    {

        $type = input('post.type');

        if ($type != 1 && $type != 2) api_return(0,'查询类型错误');

        $map['user_id'] = $this->user_id;
        $map['type']    = $type;

        $data = Db::name('user_account')->field('account_id,real_name,account,remark,status')->where($map)->find();

        api_return(1,'获取成功',$data);

    }

    /**
     * Created by xiaosong
     * E-mail:306027376@qq.com
     * 提现账号编辑
     */
    public function editAccount()
    {

        $data = request()->only(['remark','id','account','real_name','type'],'POST');

        if ($data['type'] != 1 && $data['type'] != 2) api_return(0,'账号类型错误');

        $map['user_id'] = $this->user_id;
        $map['type']    = $data['type'];

        $account = Db::name('user_account')->where($map)->find();

        if (is_numeric($data['id'])){

            if ($data['id'] != $account['account_id']) api_return(0,'参数错误');

            if ($account['status'] == 2) api_return(0,'账号正在审核中,请勿重复操作');

        }else{

            //添加时验证
            if ($account) api_return(0,'您已添加有提现账号,不能继续添加新账号');

        }

        $data['user_id'] = $this->user_id;
        $data['status']  = 2;

        $model = new UserAccount();

        $result = $model->saveChange($data);

        if ($result) api_return(1,'提交成功');
        api_return(0,$model->getError());

    }
    
    /**
     * Created by xiaosong
     * E-mail:306027376@qq.com
     * 绑定手机号码
     */
    public function bindPhone()
    {
        $user = Db::name('users')->where('user_id',$this->user_id)->field('phone')->find();
        if ($user['phone']) api_return(0,'您已绑定手机,请进行修改');
        $this->checkCode();
        $phone = input('post.phone');
        $info  = Db::name('users')->where('phone',$phone)->value('user_id');
        if ($info) api_return(0,'该手机号码已绑定其它账号!');
        $result = Db::name('users')->where('user_id',$this->user_id)->update(['phone'=>$phone]);
        if ($result)api_return(1,'绑定成功');
        api_return(0,'绑定失败');
    }



    /**
     *   分享二维码、链接获取
     */
    public function qrcode(){
        $where = db('explain')->where(['id'=>12])->value('content');
        $rule  = db('explain')->where(['id'=>13])->value('content');
        $url   = $where.'login/share?user_id='.hashid($this->user_id);
        if(!empty(cache('code'.$this->user_id))){
            $pic = cache('code'.$this->user_id);
        }else{
            $pic = code($url);
            cache('code'.$this->user_id,$pic,24*60*60);
        }
        $data['qrcode'] = $pic;
        $data['url']    = $url;
        $data['rule']   = $rule;
        $data['backGround'] = Db::name('extend')->where('id',1)->value('backGround');
        api_return(1,'',$data);
    }


    /**
     * Created by xiaosong
     * E-mail:306027376@qq.com
     * 根据用户当前等级和当前经验获取下一等级信息
     */
    protected function nextLevel($level,$experience)
    {

//        var_dump($level,$experience);exit;
        $rows = Db::name('user_level')->cache(300)->select();

        $array = array_key($rows,'level');

        $key = $level+1;
        $data['level']          = $level;
        $data['color']          = $array[$level]['color']??'';
        $data['nexLevel']       = $array[$key]['level'];
        $data['nexColor']       = $array[$key]['color']??'';
        $data['experience']     = $array[$key]['experience'];
        $data['nextExperience'] = $array[$key]['experience'] - $experience;
        if ($data['nextExperience'] < 0){
            $data['nextExperience'] = 0;
        }
        return $data;
    }

    /**
     * Created by xiaosong
     * E-mail:4155433@gmail.com
     * 根据经验值及当前等级获取应该修改的等级  用于升级时判断
     */
    protected function levelNum($experience = 0,$level = 0)
    {
        $rows = Db::name('user_level')->cache(300)->select();

        $array = array_key($rows,'level');

        $max = count($array);
        for ($i = $level;$i <= $max;$i++){
            $options = ['options'=>['min_range'=>$array[$i-1]['experience']+1,'max_range'=>$array[$i]['experience']]];
            if(
                filter_var($experience, FILTER_VALIDATE_INT, $options) !== false
            ){
                return $array[$i]['level'];
            }
        }
        return false;

    }


    /**
     * Created by xiaosong
     * E-mail:306027376@qq.com
     * 获取用户会员信息
     */
    public function level()
    {

        $data = $this->nextLevel($this->userExtra('level'),$this->userExtra('experience'));

        api_return(1,'获取成功',$data);

    }

    /**
     * Created by xiaosong
     * E-mail:4155433@gmail.com
     * 修改用户配置信息
     */
    public function editExtra()
    {

        $result = self::updateUserExtend($this->user_id);

        if ($result !== false){
            api_return(1,'修改成功');
        }
        api_return(0,'修改失败');
    }


    /**
     * Created by xiaosong
     * E-mail:4155433@gmail.com
     * 根据用户id和要购买的贵族id获取用户购买贵族所需的价格、赠送金额和购买后过期时间
     */
    protected function noblePrice(int $user_id)
    {
        $data = request()->only(['noble_id'],'post');
        $noble = Db::name('noble')->where('noble_id',$data['noble_id'])->cache(60)->find();
        if (!$noble) api_return(0,'参数错误');
        //获取用户当前贵族信息
        $userExtra = $this->userExtra('noble_id,noble_time',$user_id);
        $data['noble_time'] = time() + Time::daysToSecond(31);
        if (
            $data['noble_id'] == $userExtra['noble_id'] &&
            $userExtra['noble_time'] + Time::daysToSecond(31) > time()
        ){
            //处于续费保护期内
            $renew_rebate = $this->extend('renew_rebate');
            $rebate = bcdiv($renew_rebate,100,2);
            if ($userExtra['noble_time'] > time()){
                $data['noble_time'] = $userExtra['noble_time'] + Time::daysToSecond(31);
            }
        }else{
            $rebate = 1;
        }
        $data['price'] = bcmul($noble['price'],$rebate,2);
        $data['give']  = bcmul($noble['give'],$rebate,2);
        $data['noble_name'] = $noble['noble_name'];
        return $data;
    }


    /**
     * 第三方账号绑定
     */
    public function thirdBind()
    {

        $data = request()->only(['type','open_id','post']);

        $array = ['wx','qq','wb'];//允许的第三方登录方式

        if (!in_array($data['type'],$array)){
            api_return(0,'无此登录方式');
        }

        $map[$data['type']] = $data['open_id'];
        $userInfo = Db::name('users')->where($map)->find();

        if ($userInfo && $userInfo['user_id'] != $this->user_id){
            api_return(0,'已绑定其他账号!');
        }

        $result = Db::name('users')->where('user_id',$this->user_id)->update([$data['type']=>$data['open_id']]);

        if ($result){
            api_return(1,'绑定成功');
        }
        api_return();

    }

    /**
     * Created by xiaosong
     * E-mail:4155433@gmail.com
     * 礼物赠送成功处理
     */
    protected function gift(array $data,$user_id = null){

        $userIds = explode(',',$data['to_user']);

        $item['room_id'] = $data['room_id']??0;
        $item['gift_id'] = $data['id'];
        $item['num']     = $data['num']??1;
        if (!$user_id){
            $item['user_id'] = dehashid($data['user_id']);
        }else{
            $item['user_id'] = $user_id;
        }
        $item['total']   = $data['total']??1;
        $item['create_time'] = time();
        $item['update_time'] = time();

        $gift = Db::name('gift')->where('gift_id',$data['id'])->cache(3)->find();

        $detail['type'] = 1;
        $detail['title'] = '来自'.$this->userInfo('nick_name',$item['user_id']).'的'.$gift['gift_name'].'x'.$item['num'];
        $detail['remark'] = '收入';
        $detail['create_time'] = time();
        $detail['update_time'] = time();
        $ratio = $this->extend('gift_ratio') / 100;
        $charge = bcmul($item['total'],$ratio,2);
        $detail['money']    = bcsub($item['total'],$charge,2);
        $detail2['type']    = 2;
        $detail2['remark']  = '消费';
        $detail2['money']   = $item['total'];
        $detail2['user_id'] = $item['user_id'];
        $detail2['create_time'] = time();
        $detail2['update_time'] = time();

        $model = new Logic();
        $model->changeTable('gift_record');

        $array    = [];
        $details  = [];
        $details2 = [];
        foreach ($userIds as $k => $v){

            $item['to_user'] = dehashid($v);
            if (is_numeric($item['to_user'])){
                $array[] = $item;

                $detail['user_id'] = $item['to_user'];
                $detail2['title']  = '打赏'.$this->userInfo('nick_name',$item['to_user']).$gift['gift_name'].'x'.$item['num'];
                $details[] = $detail;
                $details2[] = $detail2;
                Db::name('users')->where('user_id',$item['to_user'])->setInc('cash',$detail['money']);

                //TODO 发送融云消息
            }
        }

        $model->insertAll($array);
        Db::name('money_detail')->insertAll($details);
        Db::name('money_detail')->insertAll($details2);
        if ($data['room_id'] != 0){
            //赠送给麦上用户时判断是否需要进行麦上打赏统计
            if (isset($data['countInfo']) && !empty($data['countInfo'])){
                $class = new Wheat();
                $wheat = $class->getWheat($data['room_id']);
                if ($wheat){
                    $countInfo = explode(',',$data['countInfo']);
                    foreach ($countInfo as $k => $v){
                        if ($wheat[$v-1]['status'] == 1){
                            $wheat[$v-1]['count'] = num($wheat[$v-1]['count']+$item['total']);
                        }
                    }

                    $class->setWheat($data['room_id'],$wheat);
                    $this->refreshWheat($data['room_id'],$wheat);
                }

            }

            addHot($data['room_id'],$data['price']);
        }
    }



    public function feedBack()
    {
        $user_id = $this->user_id;
        $param = request()->post();
        $param['user_id'] = $user_id;
        $logic = new \app\common\logic\Opinion();
        $res = $logic->saveOpinion($param);
        if($res['code']==1){
            api_return(1,'反馈成功','');
        }
        api_return(0,$res['msg']);
    }

}
